<template>

    <div class="flex_bw_start" style="height: 100%;">
        <div style="width: 14%; height: 96%;  ">
            <div class="page-title margin-bottom-10" style="transform: translateX(10px);">
                {{ '仓库管理' }}
            </div>

            <div class="table-box-left">

                <div class="card_title"
                    style="display: flex; justify-content: space-between; flex-direction: row; align-items: center">
                    <div class="card_title_text">产品分组</div>
                    <div>
                        <el-icon>
                            <Search class="icon_hover" />
                        </el-icon>

                    </div>
                </div>

                <div class="full-height-card" style="overflow-y: scroll">
                    <div class="button-container"></div>
                    <el-tree ref="treeRef" highlight-current class="full-height-tree"
                    :data="Array.isArray(departmentTree) ? departmentTree : []" node-key="id" :props="treeProps"
                    :default-expanded-keys="departmentTree.length > 0 ? [departmentTree[0].id] : []"
                    :default-checked-keys="departmentTree.length > 0 ? [departmentTree[0].id] : []"
                    :current-node-key="departmentTree.length > 0 ? departmentTree[0].id : undefined" accordion
                    @node-click="handleNodeClick">
                    <!-- <template #default="scope">
                        <div class="custom-tree-node">
                            <span :class="{ 'disabled-node': scope.node.data.status === 0 }">{{ scope.node.label
                            }}</span>
                            <span class="operation-icons">
                                <el-dropdown trigger="click" @command="handleCommand">
                                    <el-icon class="custom-icon">
                                        <Tools color="#172B4D" />
                                    </el-icon>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item
                                                :command="{ type: 'edit', data: scope.node.data }">编辑</el-dropdown-item>
                                            <el-dropdown-item
                                                :command="{ type: 'delete', data: scope.node.data }">删除</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </span>
                        </div>
                    </template> -->
                </el-tree>
                </div>
            </div>
        </div>


        <div style="width: 84%; height: 100%; padding-top: 16px;" >

            <div class="page-box">
           

                <div class="page-search">
                    <div class="search-box" :style="{ height: IsHeight }">
                        <el-input v-model="pageData.keywords" placeholder="产品名称/规格型号"
                            style="width: 200px; margin-right: 10px; margin-bottom: 10px;" @input="getAlltabeData" />
                            <el-select clearable @change="getAlltabeData" v-model="pageData.warehouse_id" placeholder="请选择仓库" style="width: 200px; margin-right: 10px; margin-bottom: 10px;">
                                <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id"></el-option>   
                            </el-select>
                    </div>

                    <div class="search-btn">
                        <div class="btn_item" @click="handleClickHeight">
                            <img class="btn_img" src="@/assets/sx.png" alt=""> <span> 高级筛选 </span>
                        </div>
                      

                    </div>

                </div>
                <!-- <div class="search-btn-right" style="top: -40px; right: -10px;">
                    <el-button color="#626aef" type="primary" @click="handleClickAdd('main')"> 其他入库 </el-button>
                </div> -->
            </div>

            <div class="table-box flex_bw_start">

                <el-table :data="tabeData" style="width: 100%" v-loading="loading" border
                    :row-class-name="tableRowClassName" default-expand-all row-key="id">
                    
                    <el-table-column align="center" prop="title" label="产品名称" width="180">
                        <template #default="scope">
                            <div >
                                <span>{{ scope.row.product.name }}</span>
                            </div>
                      
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="code" label="产品编码" width="120" >
                        <template #default="scope">
                            <div>{{ scope.row.product.no }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="house_type_name" label="规格型号" width="120" >
                        <template #default="scope">
                            <div>{{ scope.row.product.specification }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="open_unit_name" label="单位" width="120" >
                        <template #default="scope">
                            <div>{{ scope.row.product.open_unit_name }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="manager" label="库存数量" width="100" >
                        <template #default="scope"> 
                            <div>{{ scope.row.stock_num }}</div>
                        </template>
                    </el-table-column>
    
                    <el-table-column align="center" prop="service_project" label="产品图片" width="150" >
                        <template #default="scope"> 
                            <el-image
                                v-if="scope.row.product.img.length > 0"
                                :src="scope.row.product.img[0]"
                                style="width: 100px; height: 100px; cursor: pointer;"
                                :preview-src-list="[scope.row.product.img[0]]"
                                :preview-teleported="true"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="remark" label="所属仓库" min-width="200">
                        <template #default="scope">
                            <div>{{ scope.row.warehouse_name }}</div>
                           
                        </template>
                    </el-table-column>
                    <!-- <el-table-column fixed="right" label="操作" width="100" align="center">
                        <template #default="scope">
                            <div class="btn-box">
                                <el-button plain size="small" type="primary"
                                    @click="handleClickEdit(scope.row)">其他出库</el-button>
                     
                            </div>
                        </template>
                    </el-table-column> -->
                </el-table>
            </div>

        </div>
    </div>


    <!-- 分页 -->
    <Pagination class="pagination" @pageSize="pageSize" @getPage="getPage" :page="pageData.page"
        :page-size="pageData.page_size" :total="total" />
    <!-- 入库 -->
    <storeDialog v-model:dialogVisible="isShow" :dialogType="dialogType" :dialogRow="dialogRow" @submit="handleSubmit" />
    <!-- 出库 -->
     <OutboundDialog v-model:dialogVisible="OutboundVisible" :dialogType="dialogType" :dialogRow="dialogRow" />
</template>

<script setup lang="ts">

import { ref, onMounted, watch } from "vue";
import Pagination from "@/components/Pagination.vue";
import { ElMessageBox, ElMessage } from 'element-plus';
import { ElTree } from 'element-plus';
import api from "@/api";
import storeDialog from "./components/storeDialog.vue";
import OutboundDialog from "./components/OutboundDialog.vue";


import { dataType, ApiResponse } from "@/utils/publicType";
// 定义仓库数据类型
interface Warehouse {
    id: string | number;
    title: string;
    code: string;
    house_type?: string;
    house_type_name?: string;
    category_name?: string;
    manager?: string;
    phone?: string;
    address?: string;
    remark?: string;
    parent_id?: string | number;
    parent_name?: string;
    children?: Warehouse[];
    create_time?: string;
    creator?: string;
    rowNumber?: number;
    name?: string;
}


let IsHeight = ref<number | string>(0);
const isShow = ref<boolean>(false);

let dialogType = ref<string>('');
let dialogRow = ref<Warehouse>({}  as Warehouse);
let OutboundVisible = ref<boolean>(false);

let TreeId = ref<number>(0);

const pageData = ref({
    page: 1,
    page_size: 10,
    keywords: "",
    spu_id: 0,
    warehouse_id: "" ,   
});
const total = ref(0);
const tabeData = ref<Warehouse[]>([]);


const treeProps = {
    children: "children",
    label: "name",
};

interface TreeData {
    id: number;
    name: string;
    parent_id: number;

};

let nub = ref<number>(0);
const handleClickHeight = () => {
    nub.value++;
    if (nub.value % 2 == 1) {
        IsHeight.value = '40px';
    } else {
        IsHeight.value = '0px';
    }
}

const pageSize = (e: number) => {
    pageData.value.page_size = e;
    getAlltabeData();
}
const getPage = (e: number) => {
    pageData.value.page = e;
    getAlltabeData();
}
onMounted(async () => {
    await getGroupTree();
    await getAlltabeData();
    //仓库
    await getWarehouseList();
    // 确保树加载完成后选中第一个节点
    if (departmentTree.value && departmentTree.value.length > 0) {
        const firstNode = departmentTree.value[0];
        handleNodeClick(firstNode);
    }
})

let warehouseList = ref<Warehouse[]>([]);
const getWarehouseList = async () => {
    let res = await api.publicFun.getWarehouseList();
    if(res.code == 200){
        console.log(res,'[[[[[[]]]]]]');
        warehouseList.value = res.data as Warehouse[];
    }
}


// 模拟部门数据
const departmentTree = ref<TreeData[]>([]);
// 获取产品分组树
const getGroupTree = async () => {
    try {
        const res: ApiResponse<TreeData> = await api.productbasics.getproductList({ page: 'all' });
        console.log(res, 'resXXX');
        if (res.code == 200) {
            departmentTree.value = res.data as TreeData[];
            console.log('获取产品分组树成功:', departmentTree.value);
            if (departmentTree.value && departmentTree.value.length > 0) {
                TreeId.value = departmentTree.value[0].id;
                pageData.value.spu_id = TreeId.value;
                console.log('设置默认选中分组ID:', TreeId.value);

                // 确保树加载完成后选中第一个节点
                nextTick(() => {
                    if (treeRef.value) {
                        treeRef.value.setCurrentKey(TreeId.value);
                    }
                });
            } else {
                console.warn('产品分组树为空');
            }
        
        } else {
            console.error('获取产品分组树失败:', res.message);
        }
    } catch (error) {
        console.error('获取产品分组树异常:', error);
    }
}

// 树组件引用
const treeRef = ref<InstanceType<typeof ElTree>>();
// 节点点击处理
const handleNodeClick = (data: any) => {

    TreeId.value = data.id;
    pageData.value.spu_id = data.id;
    getAlltabeData();
    if (treeRef.value) {
        // 设置当前选中节点
        treeRef.value.setCurrentKey(data.id);
    }
};

// 设置行样式
const tableRowClassName = ({ row }: { row: Warehouse }) => {
    if (row.parent_id) {
        return 'sub-warehouse-row';
    }
    return '';
};

// 获取仓库列表
const getAlltabeData = async () => {
    loading.value = true;
    try {
        let res = await api.product.product_stock_list(pageData.value);

        if(res.code == 200){
            console.log(res, 'res.data.data');
            
            tabeData.value = res.data.data as Warehouse[];
            total.value = res.data.pager.total_records;
        }

   
    } catch (error) {
        console.error('获取仓库列表失败', error);
    } finally {
        loading.value = false;
    }
};

const loading = ref(false);



// 提交表单回调
const handleSubmit = () => {
    getAlltabeData();
}



</script>

<style lang="scss" scoped>
::v-deep .operation-icons {
    display: inline-block;
    transform: translate(50px, 3px) !important;
}

.table-box-left {
    border-radius: 2px;
    padding: 0 10px;
    box-sizing: border-box;
    min-height: 90%;

    width: 100%;
    padding-bottom: 20px;

    background-color: rgb(245, 248, 253);

    .card_title {
        padding: 20px 16px 10px 16px;
        margin-bottom: 10px;

        .card_title_text {
            text-shadow: 2px 2px 6px #383737a3;
        }
    }
}


::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #7962ef15;
    color: var(--el-color-btn);
}

.full-height-card {
    height: 750px;
    background-color: #fff;
    padding: 10px 8px;
    box-sizing: border-box;
    overflow-y: auto;
}

.btn-box {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap: 5px;
}

.main-warehouse {
    font-weight: bold;
    color: #333;
}

// 输入框样式
:deep(.el-input__wrapper) {
    background-color: rgba(250, 252, 251, 1);
}

//表格样式
:deep(.el-table) {
    --el-table-header-bg-color: rgba(235, 236, 240, 1);
}

:deep(.el-table thead) {
    color: #444;
}

// 子仓库行样式
:deep(.sub-warehouse-row) {
    background-color: #fef6e5;
}

//分页样式
.pagination {
    width: calc(100% - 300px);
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding-top: 10px;
    border-top: 1px solid #98989848;
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: #000 !important;
}
</style>